<?php
/**
 * 销售补贴
 */
namespace app\manage\plugins\xiaoshou;
use think\Hook;
use think\Controller;
use think\Db;

use app\common\cache\CacheData;

class Plugin extends Controller{

	public static $plugin_dir = 'xiaoshou';

	public static function init(){
		//Hook::add('addMember',__CLASS__);
	}

	public static function getInstance(){
		$plugin = new Plugin;
		return $plugin;
	}

	/**
	 * 配置页面数据
	 * @return [type] [description]
	 */
	public function data_config(){
		$coins = \app\common\query\Coin::coinData();
		$coins = array_values($coins);
		$levels = \app\common\query\Level::levelData();
		return [
			'plugin_dir' => self::$plugin_dir,
			'coins' => $coins,
			'levels' => $levels,
		];
	}

	/**
	 * 记录页面数据
	 * @return [type] [description]
	 */
	public function data_data(){
		$coins = \app\common\query\Coin::coinData();
		$coins = array_values($coins);
		$levels = \app\common\query\Level::levelData();
		return [
			'plugin_dir' => self::$plugin_dir,
			'coins' => $coins,
			'levels' => $levels,
		];
	}

	/**
	 * 保存货币配置
	 * @return [type] [description]
	 */
	public function saveCoinConfig(){
		$params = $this->request->only('data');
		$config_name = 'coin';
		
		$data = [];
		$config_total = 0;
		foreach($params['data'] as $value):
			if(isset($data[$value['coin_id']])){
				$this->error('货币类型不能重复');
			}
			$config_total += $value['config'];
			$data[$value['coin_id']] = $value;
		endforeach;

		if($config_total!=100){
			$this->error('货币配置百分比只和必须等于100%');
		}
		
		$insertData = [
			'plugin_dir' => self::$plugin_dir,
			'config_name' => $config_name,
			'config_value' => serialize($data),
		];

		$model = new \app\common\model\PluginConfig;
		if($model->where(['plugin_dir'=>$insertData['plugin_dir'],'config_name'=>$insertData['config_name']])->find()){
			// 如果存在该配置，则更新
			$model -> where([
				'plugin_dir'=>$insertData['plugin_dir'],
				'config_name'=>$insertData['config_name']
				]) -> update(['config_value'=>$insertData['config_value']]);
		}else{
			// 否则新增
			$model -> insert($insertData);
		}
		// 更新缓存
		$CACHE = CacheData::getInstance('PluginConfig');
		$CACHE->updateCache();
		$this->success('更新成功');
	}

	public function saveBonusConfig(){
		$params = $this->request->only('data');
		$config_name = 'bonus';

		$postData = $params['data'];
		// 用level_id作为数组的键名
		$data = [];
		foreach($postData as $value):
			// 倍数作为内层数组键名
			$value = array_combine(array_column($value, 'multiple'), $value);
			$data[$value[0]['level_id']] = $value;
		endforeach;

		$insertData = [
			'plugin_dir' => self::$plugin_dir,
			'config_name' => $config_name,
			'config_value' => serialize($data),
		];

		$model = new \app\common\model\PluginConfig;
		if($model->where(['plugin_dir'=>$insertData['plugin_dir'],'config_name'=>$insertData['config_name']])->find()){
			// 如果存在该配置，则更新
			$model -> where([
				'plugin_dir'=>$insertData['plugin_dir'],
				'config_name'=>$insertData['config_name']
				]) -> update(['config_value'=>$insertData['config_value']]);
		}else{
			// 否则新增
			$model -> insert($insertData);
		}
		// 更新缓存
		$CACHE = CacheData::getInstance('PluginConfig');
		$CACHE->updateCache();
		$this->success('更新成功');
	}

	/**
	 * 
	 * @param [type] &$params [description]
	 */
	public function addMember($data){
		$memberData = $data['member'];
		$score = $data['score'];
		
		//dump($data);die;

	}

	/**
	 * 结算销售补贴
	 * @return [type] [description]
	 */
	public function deal(){
		$model = new \app\common\model\MemberScore;
		$datas = $model -> where(['status'=>0]) -> select();
		$datas = collection($datas)->toArray();

		$memberQuery = new \app\common\query\Member;

		foreach($datas as $data):
			$member = $memberQuery -> getOneData(['mid'=>$data['mid']],['seter_id','area','level_id']);
			// 变更用户新增业绩记录状态
			$model -> where(['id'=>$data['id']]) -> update(['status'=>2]);
			Db::startTrans();
			try{
				if(true===$this->math($data['mid'],$member['seter_id'],$member['area'],$data['score'],$member['level_id'])){
					// 变更用户新增业绩记录状态
					$model -> where(['id'=>$data['id']]) -> update(['status'=>1]);
				}
				Db::commit();
			}catch(Exception $e){
				Db::rollback();
				// 变更用户新增业绩记录状态
				$model -> where(['id'=>$data['id']]) -> update(['status'=>3]);
				continue;
			}
		endforeach;
	}

	private function math($reason_mid,$mid,$area,$score,$level_id){
		$memberAreaScoreModel = new \app\common\model\MemberAreaScore;
		// 查询AB区剩余业绩
		$area_score = $memberAreaScoreModel -> where(['mid'=>$mid]) -> select();
		$area_score = collection($area_score)->toArray();

		$area_score = array_combine(array_column($area_score, 'area'), $area_score);

		$area_score[$area]['score'] = floatval($area_score[$area]['score'])+floatval($score);

		if($area_score[1]['score']==$area_score[2]['score']&&$area_score[1]['score']!=0){
			// 剩余业绩
			$restScore[1] = 0;
			$restScore[2] = 0;
			// 待结算业绩
			$mathScore = $area_score[1]['score'];
		}else if($area_score[1]['score']>$area_score[2]['score']){
			// 剩余业绩
			$restScore[1] = $area_score[1]['score']-$area_score[2]['score'];
			$restScore[2] = 0;
			// 待结算业绩
			$mathScore = $area_score[2]['score'];
		}else if($area_score[1]['score']<$area_score[2]['score']){
			// 剩余业绩
			$restScore[1] = 0;
			$restScore[2] = $area_score[2]['score']-$area_score[1]['score'];
			// 待结算业绩
			$mathScore = $area_score[1]['score'];
		}
		
		if($mathScore!=0):

			// 获取插件配置
			$pluginConfigQuery = new \app\common\query\PluginConfig;
			// 货币配置
			$coinConfig = $pluginConfigQuery::pluginConfig(self::$plugin_dir,'coin');
			$coinConfig = unserialize($coinConfig['config_value']);
			// 奖金配置
			$bonusConfig = $pluginConfigQuery::pluginConfig(self::$plugin_dir,'bonus');
			$bonusConfig = unserialize($bonusConfig['config_value']);
			// 获取当前会员等级配置
			$bonusConfig = $bonusConfig[$level_id];
			// 计算当前会员销售补贴倍数，并获取对应比率配置
			$multiple = 0;
			$bonusConfig = $bonusConfig[$multiple];
			$rate = $bonusConfig['rate'];
			// 计算奖金
			$bonus = $score*$rate/100;
			// 货币分配
			$pluginDataModel = new \app\common\model\PluginData;
			$data =[];
			foreach($coinConfig as $config):
				// 插件记录
				$data[] = [
					'plugin_dir' => self::$plugin_dir,
					'reason_mid' => $reason_mid,
					'effect_mid' => $mid,
					'coin_id' => $config['coin_id'],
					'amount' => $bonus*$config['config']/100,
					'remark' => '【'.$reason_mid.'】产生销售补贴',
				];
			endforeach;
			$pluginDataModel -> saveAll($data);

		endif;

		// 更新剩余业绩
		$memberAreaScoreModel ->where(['mid'=>$mid,'area'=>1]) -> update(['score'=>$restScore[1]]);
		$memberAreaScoreModel ->where(['mid'=>$mid,'area'=>2]) -> update(['score'=>$restScore[2]]);

		$memberModel = new \app\common\model\Member;
		$member = $memberModel -> where(['mid'=>$mid]) -> field(['area','seter_id','level_id']) -> find();
		if($member['seter_id']){
			// 递归
			return $this->math($reason_mid,$member['seter_id'],$member['area'],$score,$member['level_id']);
		}else{
			return true;
		}

	}

}